package com.lizemin.controller;

import cn.hutool.core.util.StrUtil;
import com.lizemin.constant.Constants;
import com.lizemin.entity.User;
import com.lizemin.listener.SessionManagementListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author lzm
 * @date 2025/4/6 9:58
 * @description
 */
@RestController
public class AdminController {

    @Autowired
    SessionManagementListener sessionManagementListener;

    @Autowired
    HttpSession httpSession;

    /**
     * 获取所有在线用户
     */
    @GetMapping("/getAllActiveUsers")
    public List<User> getAllActiveUsers() {
        validatePermission();
        List<HttpSession> sessions = sessionManagementListener.getAllSessions();
        return sessions.stream()
                .map(session -> {
                    User user = (User) session.getAttribute(Constants.LOGIN_STATUS);
                    user.setSessionId(session.getId());
                    return user;
                })
                .collect(Collectors.toList());
    }

    /**
     * 获取在线用户数
     * @return 在线用户数
     */
    @GetMapping("/getActiveSessionCount")
    public int getActiveSessionCount() {
        validatePermission();
        return sessionManagementListener.getActiveSessionCount();
    }

    /**
     * 将特定用户踢下线
     *
     * @param sessionId sessionId
     */
    @GetMapping("/remove")
    public String getActiveSessionCount(String sessionId) {
        validatePermission();
        if (StrUtil.isBlank(sessionId)) {
            throw new RuntimeException("sessionId不能为空");
        }
        sessionManagementListener.removeSession(sessionId);
        return "success";
    }


    /**
     * 验证权限
     */
    private void validatePermission() {
        User cuurentUser = (User) httpSession.getAttribute(Constants.LOGIN_STATUS);
        if (Objects.isNull(cuurentUser)) {
            throw new RuntimeException("用户未登录");
        }
        String role = cuurentUser.getRole();
        if (!StrUtil.equals(role, "admin")) {
            throw new RuntimeException("权限不足");
        }
    }


}
